/**
 * 物料单位选择项
 * @author Canaan
 * @date 2019/8/14 9:41
 */
export default {

  state: {
    materialUnitOptions: {
      refNum: 0,          //被组件引用次数
      loading: false,     //数据是否加载中
      brandId: null,      //所属品牌
      options: []         //具体的选项列表
    }
  },
  actions: {
    loadMaterialUnitOptions({commit, state}, vue) {

      //如果没有被人引用，那么不加载数据
      if (state.materialUnitOptions.refNum <= 0) {
        return;
      }

      //如果正在加，就不处理
      if (state.materialUnitOptions.loading) {
        return;
      }

      let brandId;
      if (!state.userContext.id) {
        return; //当前用户还未加载
      } else if (state.userContext.role === 'BRAND') {
        brandId = state.userContext.brand.id;
      } else if (state.userContext.role === 'STORE') {
        brandId = state.userContext.store.brand.id;
      }

      if (!brandId) {
        return;
      }

      //如果品牌相同就不加载
      if (brandId === state.materialUnitOptions.brandId) {
        return;
      }

      commit('materialUnitOptions', {cmd: "loading", val: true});
      commit('materialUnitOptions', {cmd: "brandId", val: brandId});

      vue.$ajax.get('material_unit/list', {
          params: {
            brandId: brandId
          }
        }
      ).then(res => {
        commit('materialUnitOptions', {cmd: "loading", val: false});
        if (res.code !== 'ok') {
          throw res.msg;
        }
        commit('materialUnitOptions', {cmd: "options", val: res.data.rows || []});
      });

    }

  },
  mutations: {
    clearMaterialUnitOptions({materialUnitOptions}) {
      materialUnitOptions.options = [];
    },
    materialUnitOptions({materialUnitOptions}, {cmd, val}) {
      switch (cmd) {
        case "loading":
          materialUnitOptions.loading = val;
          break;
        case "options":
          materialUnitOptions.options = val;
          break;
        case "minusRef":
          materialUnitOptions.refNum = Math.max(0, materialUnitOptions.refNum - 1);
          break;
        case "plusRef":
          materialUnitOptions.refNum++;
          break;
        case "brandId":
          materialUnitOptions.brandId = val;
          break;
        default:
          throw "materialUnitOptions 未知的命令" + cmd;
      }

    }

  }


}
